<template>
  <view class="content screen-width">
    <topBar :title="`政策订阅`" />
    <view class="searchBar flex">
      <view class="search">
        <input type="text" placeholder="请输入你要订阅的部门或地区" v-model="getKeyword" />
        <image src="../../static/policy/search.png" mode @tap="changeSearch" />
      </view>
    </view>
    <view class="selectBar">
      <span>
        <input type="text" :value="address ? address : '地区'" @tap="showArea" disabled />
        <image src="../../static/proty/botton_icon.png" mode />
      </span>
      <view @click="toCurrent" style="color: #1678ff;background: #fff;padding: 10upx;">切换当前定位</view>
      <view class="area_R">共为您找到{{ total}}个部门</view>
    </view>
    <!-- 未搜索 -->
    <!-- <view class="hotcontent" v-show="!isSearch">
			<view class="hotTitle">热门推荐</view>
			<view class="hotArticle">
				<ul>
					<li v-for="(item, index) in SubscriptionData" :key="index">
						<text class="multipleRow" v-html="item.departmentName"></text>
						<button v-if="item.whetherAttention == 0" @tap="isSubscription(item.whetherAttention,item.id,index)">订阅</button>
						<button class="active" v-if="item.whetherAttention != 0" @tap="isSubscription(item.whetherAttention,item.id,index)">已订阅</button>
					</li>
				</ul>
			</view>
			<view class="batch" @tap="next">
				<image src="../../static/policy/batch.png" more="" v-show="getKeyword==''&&areaSubscriptList.length<0">换一批
			</view>
    </view>-->
    <!-- 搜索结果 -->
    <view class="hot_result" v-show="areaSubscriptList.length>0">
      <view class="area_title">
        <view class="area_L">{{address? address : '地区'}}</view>
        <!-- <view class="area_R">共为您找到{{areaSubscriptList.length}}个部门</view> -->
      </view>
      <!-- 省份 -->
      <view class="result_item" v-for="(item, index) in areaSubscriptList" :key="index">
        <view class="text">
          <view class="text_L">{{item.name}}</view>
          <view class="text_R">
            <image src="../../static/proty/more.png" mode @tap="selectAreaItem(item)" />
          </view>
        </view>
        <view class="result_content">
          <ul>
            <li v-for="(v, i) in item.childs" :key="i">
              <text @click="toDepartPolicy(v.id)" class="multipleRow">{{v.departmentName}}</text>
              <button
                v-if="v.whetherAttention ==0"
                @tap="isSubscription(v.whetherAttention,v.id, dataItem.city ? 2:1)"
              >订阅</button>
              <button
                class="active"
                v-if="v.whetherAttention !=0"
                @tap="isSubscription(v.whetherAttention,v.id, dataItem.city ? 2:1)"
              >已订阅</button>
            </li>
          </ul>
        </view>
        <!-- 城市和区 -->
        <view
          class="city_area"
          v-for="(i,t) in item.departments"
          :key="t"
          v-show="item&&item.departments.length"
        >
          <view class="text">
            <view class="text_L">{{i.name}}</view>
            <view class="text_R">
              <image src="../../static/proty/more.png" mode @tap="selectAreaItem(i.name)" />
            </view>
          </view>
          <view class="result_content">
            <ul>
              <li v-for="(j, k) in i.childs" :key="k">
                <text @click="toDepartPolicy(j.id)" class="multipleRow">{{j.departmentName}}</text>
                <button
                  v-if="j.whetherAttention==0"
                  @tap="isSubscription(j.whetherAttention,j.id, !dataItem.city ? 2:3,t)"
                >订阅</button>
                <button
                  class="active"
                  v-if="j.whetherAttention !=0"
                  @tap="isSubscription(j.whetherAttention,j.id,!dataItem.city ? 2:3,t)"
                >已订阅</button>
              </li>
            </ul>
          </view>
        </view>
      </view>
    </view>
    <view class="noData" v-show="areaSubscriptList.length== 0 ">
      <text>没有更多了</text>
    </view>
    <!-- 地区 -->
    <PickerView
      ref="picker"
      :isshowArea="isshowArea"
      :type="proType"
      @affirm="affirm"
      @cancel="cancel"
    ></PickerView>
    <!-- 订阅部门选取关键字 -->
    <keyWord :mask-show="maskShow" @hidePopup="hidePopup"></keyWord>
  </view>
</template>

<script>
import topBar from "../../components/topBar.vue";
import dialoguse from "../../components/dialog.vue";
import { isWeixin, wxShareConfig } from "util/wx.js";
export default {
  components: {
    topBar,
    dialoguse
  },
  data() {
    return {
      maskShow: false,
      itemCity: "",
      itemArea: "",
      showToast: {
        msg: "请先登陆后,在操作",
        affirm: "马上登录"
      },
      isSearch: false, // 搜索状态
      show: false, // 是否显示登陆框
      isshowArea: false, // 是否显示地区
      areaList: {}, // 获取地区列表
      address: "", // 展示的地区
      dataItem: {
        province: "", // 省份
        city: "", // 城市
        area: "" //地区
      },
      getKeyword: "", // 关键字
      SubscriptionData: [], // 订阅列表数据(随机订阅列表)
      areaSubscriptList: [], // 地区订阅
      total: 0, // 获取政策订阅的条数

      valueArr: [0, 0, 0], // 用于判断当前滑动的是哪一列
      proType: 2,
      nProvince: "",
      nCity: "",

      latitude: "",
      longitude: ""
    };
  },
  onShow() {
    this.address = uni.getStorageSync("city");
    this.getSub();
  },
  onHide() {
    this.nProvince = "";
    this.nCity = "";
  },
  methods: {
    hidePopup() {
      this.maskShow = false;
    },
    // 切换当前定位
    toCurrent() {
      this.address = "";
      this.init();
    },
    // 点击下一项
    selectAreaItem(val) {
      // console.log(val);
      uni.pageScrollTo({
        // 回到顶部
        scrollTop: 0,
        duration: 0
      });
    },
    isLogin(val) {
      if (val == false) {
        this.show = false;
      }
    },
    // 点击订阅按钮
    /**
     * isAttention
     * departmentId
     * type 类型
     * pIndex 父索引
     */
    // 点击城市列表的关注
    isSubscription(isAttention, departmentId, type, pIndex) {
      let token = this.$getToken();
      if (!token) {
        uni.showModal({
          title: "提示",
          content: "请先登录后,在操作",
          confirmText: "马上登录",
          success(res) {
            if (res.confirm) {
              uni.setStorageSync("pageUrl", window.location.href);
              uni.navigateTo({
                url: "/pages/login/index"
              });
              // console.log('马上登录');
            }
          }
        });
        return;
      }
      let _this = this;
      // 点击订阅
      if (isAttention == 0) {
        // 0 代表 未关注 ( 关注接口)
        this.$post(
          "/bmj-api/api/home/departmentAttention?departmentId=" + departmentId
        ).then(res => {
          // console.log("关注接口",res)
          if (res.code == 10002) {
            uni.showModal({
              title: "提示",
              content: res.message,
              confirmText: "升级会员",
              success: function(res) {
                if (res.confirm) {
                  // 升级会员
                  uni.navigateTo({
                    url: "/pages/VIP/index"
                  });
                }
              }
            });
          } else if (res.code == 200) {
            //  console.log(res)
            if (!_this.address) {
              _this.SubscriptionData[type].whetherAttention = 1;
            } else {
              if (type == 1) {
                let i = _this.areaSubscriptList[0].childs.findIndex(el => {
                  return el.id == departmentId;
                });
                // console.log(i)
                _this.areaSubscriptList[0].childs[i].whetherAttention = 1;
              } else if (type == 2) {
                if (pIndex != undefined) {
                  // console.log(_this.areaSubscriptList[0].departments[pIndex])
                  // return
                  let i = _this.areaSubscriptList[0].departments[
                    pIndex
                  ].childs.findIndex(el => el.id == departmentId);
                  // console.log(i)
                  // return
                  _this.areaSubscriptList[0].departments[pIndex].childs[
                    i
                  ].whetherAttention = 1;
                } else {
                  let i = _this.areaSubscriptList[0].childs.findIndex(
                    el => el.id == departmentId
                  );
                  _this.areaSubscriptList[0].childs[i].whetherAttention = 1;
                }
              } else if (type == 3) {
                let i = _this.areaSubscriptList[0].departments[
                  pIndex
                ].childs.findIndex(el => el.id == departmentId);
                _this.areaSubscriptList[0].departments[pIndex].childs[
                  i
                ].whetherAttention = 1;
              }
            }
          }
        });
      } else if (isAttention == 1) {
        // 1 代表 已关注 (取消关注接口)

        uni.showModal({
          title: "提示",
          content: "您确定要取消订阅吗,取消后将不再接收该部门的政策推送",
          cancelText: "考虑一下",
          success: function(res) {
            if (res.confirm) {
              _this
                .$post(
                  "/bmj-api/api/home/cancelAttention?departmentId=" +
                    departmentId
                )
                .then(res => {
                  // console.log("取消关注接口",res)
                  if (res.code == 200) {
                    if (!_this.address) {
                      _this.SubscriptionData[type].whetherAttention = 0;
                    } else {
                      if (type == 1) {
                        let i = _this.areaSubscriptList[0].childs.findIndex(
                          el => {
                            return el.id == departmentId;
                          }
                        );
                        // console.log(i)
                        _this.areaSubscriptList[0].childs[
                          i
                        ].whetherAttention = 0;
                      } else if (type == 2) {
                        if (pIndex != undefined) {
                          // console.log(_this.areaSubscriptList[0].departments[pIndex])
                          // return
                          let i = _this.areaSubscriptList[0].departments[
                            pIndex
                          ].childs.findIndex(el => el.id == departmentId);
                          // console.log(i)
                          // return
                          _this.areaSubscriptList[0].departments[pIndex].childs[
                            i
                          ].whetherAttention = 0;
                        } else {
                          let i = _this.areaSubscriptList[0].childs.findIndex(
                            el => el.id == departmentId
                          );
                          _this.areaSubscriptList[0].childs[
                            i
                          ].whetherAttention = 0;
                        }
                      } else if (type == 3) {
                        let i = _this.areaSubscriptList[0].departments[
                          pIndex
                        ].childs.findIndex(el => el.id == departmentId);
                        _this.areaSubscriptList[0].departments[pIndex].childs[
                          i
                        ].whetherAttention = 0;
                      }

                      // _this.areaSubscriptList[index].whetherAttention = 1
                    }
                  }
                });
            }
          }
        });
      }
      // 显示登陆框
      // this.show = true;
    },
    // 选择地区的(显示地区框)
    showArea() {
      this.isshowArea = true;
    },
    // 选择地区的退出按钮
    cancel() {
      this.isshowArea = false;
    },
    // 点击换一批
    next() {
      this.getrandomList();
    },
    // 获取经纬度，腾讯地图接口解析
    init() {
      // console.log("正在定位");
      uni.showLoading({ title: "加载中" });
      var that = this;
      uni.getLocation({
        type: "gcj02",
        geocode: true,
        success: res => {
          // console.log("获取经纬度成功", res);
          this.latitude = res.latitude;
          this.longitude = res.longitude;
          // 解析地址
          this.handleLocation();
        },
        fail: err => {
          // console.log(err);
          this.init();
        }
      });
    },
    handleLocation() {
      // console.log("解析定位");
      let location = this.latitude + "," + this.longitude;
      this.$get("/bmj-api/api/tencent/getLocation", {
        location: location
      }).then(res => {
        this.$nextTick(function() {
          this.dataItem.province = ""; // 省
          this.dataItem.city = res.result.ad_info.city; // 市
          // console.log(
          //   "解析定位成功",
          //   this.dataItem.province,
          //   this.dataItem.city
          // );
          this.getSubscriptionList();
        });
      });
    },
    // 获取订阅列表
    getSub() {
      if (!this.nProvince && !this.nCity) {
        let city = uni.getStorageSync("city");
        let province = uni.getStorageSync("province");
        if (city && province) {
          this.dataItem.city = city;
          // this.dataItem.province = province;
          this.getSubscriptionList();
        } else {
          this.init();
        }
      }
      if (isWeixin()) {
        this.initShareConfig();
      }
    },
    getSubscriptionList() {
      let obj = {
        province: this.dataItem.province, // 省份
        city: this.dataItem.city, // 城市
        area: this.dataItem.area, // 地区
        departmentName: this.getKeyword, // 关键字
        pageSize: 0 // 传入页数
      };
      for (let key in obj) {
        if (!String(obj[key]).length) {
          delete obj[key];
        }
      }

      // 选择地区后数据列表的请求
      this.$get(
        "/bmj-api/api/pms/pmsDepartment/getPolicyDepartmentSubscribeInfo",
        obj
      ).then(res => {
        uni.hideLoading();
        if (res.code == 200) {
          let { departmentTotal } = res.result;

          // console.log("地区列表", res.result);
          this.total = departmentTotal;
          if (this.dataItem.province) {
            // console.log(11111111);
            // 说明是选择了省份
            this.areaSubscriptList = res.result.departmentInfo;
          } else if (this.dataItem.city) {
            // 说明是选择了城市
            // console.log(222222222);
            res.result.departmentInfo.forEach(el => {
              if (
                Object.prototype.toString.call(el.departments) ===
                "[object Array]"
              ) {
                this.areaSubscriptList = el.departments;
              }
            });
          } else if (this.dataItem.area) {
            // 说明选择了地区
            // console.log(3333333333);
            res.result.departmentInfo.forEach(el => {
              if (
                Object.prototype.toString.call(el.departments) ===
                "[object Array]"
              ) {
                this.areaSubscriptList = el.departments;
              }
            });
          } else {
            // console.log(44444444);
            res.result.departmentInfo.forEach(el => {
              if (
                Object.prototype.toString.call(el.departments) ===
                "[object Array]"
              ) {
                this.areaSubscriptList = el.departments;
              }
            });
          }
        }
      });
    },
    // 点击确定按钮
    affirm(province, city, area) {
      this.dataItem.province = province;
      this.dataItem.city = city;
      this.dataItem.area = area;
      let arr = [];
      if (this.dataItem.province) {
        arr.push(this.dataItem.province);
      }
      if (this.dataItem.province && this.dataItem.city) {
        arr.push(this.dataItem.province);
        arr.push(this.dataItem.city);
      }
      if (this.dataItem.province && this.dataItem.city && this.dataItem.area) {
        arr.push(this.dataItem.province);
        arr.push(this.dataItem.city);
        arr.push(this.dataItem.area);
      }
      let arrLen = Array.from(new Set(arr));

      for (let i = 0; i < arrLen.length; i++) {
        if (arrLen[i] === "请选择") {
          arrLen.splice(i, 1);
        }
      }
      this.isSearch = true;

      if (arrLen.length === 1) {
        this.dataItem.area = "";
        this.dataItem.city = "";
        this.dataItem.province = arrLen[0];
        this.getSubscriptionList();
      } else if (arrLen.length === 2) {
        this.dataItem.province = "";
        this.dataItem.area = "";
        this.dataItem.city = arrLen[1];
        this.getSubscriptionList();
      } else if (arrLen.length === 3) {
        this.dataItem.province = "";
        this.dataItem.city = "";
        this.dataItem.area = arrLen[2];
        this.getSubscriptionList();
      } else {
        this.address = "";
        this.getrandomList();
        // 点击退出按钮
        this.cancel();
        return;
      }
      this.address = arrLen.pop();
      this.nProvince = this.dataItem.province;
      this.nCity = this.dataItem.city;
      // 点击退出按钮
      this.cancel();
    },
    // 点击搜索内容
    changeSearch() {
      if (!this.getKeyword && !this.address) {
        this.isSearch = false;
        uni.showToast({
          title: "请输入你要查询的部门或地区",
          duration: 2000,
          icon: "none"
        });
        return;
      }
      this.isSearch = true;
      this.getSubscriptionList();
    },

    // 随机获取订阅列表
    getrandomList() {
      this.$get("/bmj-api/api/pms/pmsDepartment/randomObtainDepartment").then(
        res => {
          if (res.code == 200) {
            this.total = res.result.length;
            this.SubscriptionData = res.result;
          }
        }
      );
    },
    // 政策部门通知
    toDepartPolicy(id) {
      uni.navigateTo({
        url: `/pages/policy/departPolicy?id=${id}`
      });
    },

    initShareConfig() {
      let _this = this;
      let windowurl = window.location.href.split("#")[0];
      uni.request({
        url: "https://oldm.51bmj.cn/WeiXin/GetClientSign", //仅为示例，并非真实接口地址。
        data: {
          rawUrl: windowurl
        },
        dataType: "json",
        header: {
          "X-Requested-With": "XMLHttpRequest"
        },
        method: "GET",
        success: res => {
          if (res.statusCode == 200) {
            let { data } = res;
            let shareInfo = {
              title: "政策订阅",
              desc: "最新政策一键订阅，实时推送",
              link: window.location.href
            };
            wxShareConfig(this.$wx, data, shareInfo);
          }
        }
      });
    }
  }
};
</script>

<style lang="less" scoped>
.popup {
  height: fit-content;
  width: 100%;
  background: #fff;
}

.picker-btn {
  display: flex;
  height: 100upx;
  width: 100%;
  line-height: 100upx;
  background: #fff;
  font-size: 16px;
  z-index: 1;
  border-bottom: 1rpx solid #f8f8f8;

  .left {
    flex: 1;
    color: #0076ff;
    padding-left: 40upx;
    box-sizing: border-box;
  }

  .right {
    flex: 1;
    text-align: right;
    padding-right: 40upx;
    color: #fe4533;
    box-sizing: border-box;
  }
}

picker-view {
  width: 100%;
  height: 500rpx;
  display: relative;
}

.item {
  line-height: 100rpx;
  text-align: center;
}

.searchBar {
  height: 120rpx;
  padding: 20rpx 30rpx;
  background-color: #fff;

  .search {
    height: 80rpx;

    display: flex;
    border-radius: 15rpx;
    align-items: center;
    background-color: #f8f8f8;
    justify-content: space-around;
    padding-left: 20rpx;

    input {
      flex: 1;

      &::placeholder {
        font-size: 14px;
      }
    }

    image {
      width: 32rpx;
      height: 32rpx;
      margin: 0 30rpx;
    }
  }
}

.selectBar {
  height: 120rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;

  span {
    width: 170rpx;
    height: 60rpx;
    background-color: #fff;
    display: flex;
    padding: 0rpx 20rpx;
    align-items: center;

    image {
      width: 14rpx;
      height: 10rpx;
    }

    input {
      width: 100rpx;
      font-size: 14px;
      color: #44a2ff;
    }
  }

  .area_R {
    color: #ffaa8d;
    font-size: 13px;
  }
}

.hotcontent {
  background-color: #fff;
  padding: 0 30rpx;
  min-height: 1005rpx;

  .hotTitle {
    height: 120rpx;
    display: flex;
    align-items: center;
    color: #333333;
    font-size: 16px;
    font-weight: 700;
  }

  .hotArticle {
    ul {
      display: flex;
      flex-wrap: wrap;

      li {
        display: flex;
        align-items: center;
        height: 120rpx;
        width: 50%;
        font-size: 13px;
        padding-right: 30rpx;

        &:nth-child(2n + 2) {
          padding-right: 0rpx;
        }

        text {
          flex: 1;
        }

        button {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 80rpx;
          height: 48rpx;
          background-color: #1678ff;
          margin-left: 20rpx;
          font-size: 12px;
          border-radius: 0;
          color: #fff;
          white-space: nowrap;

          &.active {
            border-radius: 0;
            background-color: #e8f3ff;
            color: #1678ff;
          }
        }
      }
    }
  }

  .batch {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 13px;
    color: #2862ad;
    margin: 80rpx auto;
    background-color: #fff;

    image {
      width: 24rpx;
      height: 24rpx;
      margin-right: 20rpx;
    }
  }
}

/* 搜索结果的字符集 */
.hot_result {
  // margin: 0 -30rpx;
  padding-bottom: 20rpx;
  position: relative;

  .area_title {
    padding: 0 30rpx;
    display: flex;
    background-color: #fff;
    height: 120rpx;
    justify-content: space-between;
    align-items: center;

    &.active {
      // position:fixed;
      // right:0;
      // top:0rpx;
      // background:none;
    }

    .area_L {
      font-weight: 700;
      color: #333;
      font-size: 16px;
    }

    .area_R {
      // color: #ffaa8d;
      // font-size: 26rpx;
    }
  }

  .result_item {
    padding: 0 30rpx;

    // margin: 0 -30rpx;
    .text {
      padding: 0 30rpx;
      height: 80rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .text_L {
        color: #333333;
      }

      .text_R {
        width: 50rpx;
        height: 50rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }

    .result_content {
      background-color: #fff;
      padding: 0 30rpx;

      ul {
        display: flex;
        flex-wrap: wrap;
        background-color: #fff;

        li {
          height: 120rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 50%;
          font-size: 13px;
          padding-right: 20rpx;

          &:nth-child(2n) {
            padding-right: 0rpx;
            padding-left: 20rpx;
          }

          text {
            flex: 1;
          }

          button {
            border: 0;
            color: #fff;
            display: flex;
            align-items: center;
            background-color: #1678ff;
            font-size: 12px;
            border-radius: 0;
            padding: 6rpx 20rpx;

            &.active {
              border-radius: 0;
              background-color: #e8f3ff;
              color: #1678ff;
            }
          }
        }
      }
    }
  }
}

.noData {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  height: 40rpx;
  color: #aaaaaa;
  margin: 40rpx auto;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
</style>
